#!/usr/bin/python

#!/usr/bin/python

import os
import subprocess
import sys
import time

global PIPE
global ETHER_INTERFACE

PIPE = subprocess.PIPE
ETHER_INTERFACE = 'eth0'
TIME_TO_SLEEP = 1

def del_arp_item_from_arp_table( i ):
    os.system( '/usr/sbin/arp -d %s' % i )

def add_arp_item_to_arp_table( i, m ):

    os.system( '/usr/sbin/arp -s %s %s' % ( i, m ) )
    #return True

def check_ping( i ):
    """1 is unreachable , 0 is live"""
    return_code = subprocess.call( ['/bin/ping', '-w1', '-c1', '%s' % i] )
    if return_code == 0:
        return True
    else:
        return False

def map_ip_to_mac():
    """return two disct , dynamic static """
    _ip_to_mac_map_dynamic = {}
    _ip_to_mac_map_static = {}
    p = subprocess.Popen( '/usr/sbin/arp -an -i %s' % ETHER_INTERFACE, shell=True, stdout=PIPE, close_fds=True )
    ( child_stdin, child_stdout, child_stderr ) = ( p.stdin, p.stdout, p.stderr )
    res_arp_tables = child_stdout.readlines()

    for x in res_arp_tables:
        _pre_map = x.split()
        if len( _pre_map ) < 7:
            pass
        elif len( _pre_map ) == 7:
            mac = _pre_map[3]
            ip = _pre_map[1][1:-1]
            _ip_to_mac_map_dynamic[ip] = mac
        elif len( _pre_map ) == 8:
            mac = _pre_map[3]
            ip = _pre_map[1][1:-1]
            _ip_to_mac_map_static[ip] = mac

    return _ip_to_mac_map_dynamic, _ip_to_mac_map_static

def main():
    while 1:
        dynamic_arp , static_arp = map_ip_to_mac()

        #print dynamic_arp , static_arp
        #sys.exit()
        for dynamic_ip, dynamic_mac in dynamic_arp.iteritems():
            if check_ping( dynamic_ip ):
                # host alive ,add it to static arp table
                print '%s host alive ,add it to static arp table' % dynamic_ip
                add_arp_item_to_arp_table( dynamic_ip, dynamic_mac )
            else:
                # host death, remove it from arp table
                print '%s host death, remove it from arp table' % dynamic_ip
                del_arp_item_from_arp_table( dynamic_ip )
                time.sleep( TIME_TO_SLEEP )

        for static_ip, static_mac in static_arp.iteritems():
            if check_ping( static_ip ):
                print '%s host alive , do nothing in static arp table' % static_ip
            else:
                print '%s host death, remove it from static arp table' % static_ip
                del_arp_item_from_arp_table( static_ip )
                time.sleep( TIME_TO_SLEEP )

        #break
        time.sleep( TIME_TO_SLEEP )

if __name__ == '__main__':
    main()
